package com.david.scan

import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.app.Dialog
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.david.scan.king.util.CodeUtils
import com.king.camera.scan.CameraScan
import com.king.camera.scan.util.LogUtils
import com.king.camera.scan.util.PermissionUtils
import java.util.concurrent.Executors


/**
 * 参考链接：https://gitee.com/jenly1314/ZXingLite
 */
class MainActivity : AppCompatActivity(), OnClickListener {
    private val REQUEST_CODE_SCAN = 0x01
    private val REQUEST_CODE_PHOTO = 0x02
    private val REQUEST_CODE_READ_EXTERNAL_STORAGE = 0x99

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            requestFilePermission(this, {

            })
        }

        findViewById<View>(R.id.create_btn).setOnClickListener {
            startActivity(Intent(this, CreateQrActivity::class.java))
            //val intent = Intent(this, CodeActivity::class.java)
            //intent.putExtra(KEY_IS_QR_CODE, true)
            //intent.putExtra(KEY_TITLE, title)
            //startActivity(intent)
        }

        findViewById<View>(R.id.scan_btn).setOnClickListener {
            startActivity(Intent(this, ScanActivity::class.java))
            //val optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.`in`, R.anim.out)
            //val intent = Intent(this, QRCodeScanActivity::class.java)
            //startActivityForResult(intent, 100)
            //startActivity(Intent(this, CaptureActivity::class.java))
        }


        findViewById<View>(R.id.decode_img).setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "image/*"
            startActivityForResult(intent, 1000)
        }

        findViewById<View>(R.id.showResultDialog).setOnClickListener {
            dialog?.show()
        }

        val androidId: String = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
        Log.d("Android", "Android ID : $androidId")


        dialog = CodeResultDialog("hahahhah", this, R.style.BottomDialogTheme)
    }

    private var dialog: Dialog? = null


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && data != null) {
            when (requestCode) {
                REQUEST_CODE_SCAN -> {
                    val result = CameraScan.parseScanResult(data)
                    showToast(result)
                }

                REQUEST_CODE_PHOTO -> parsePhoto(data)
            }
        }
    }

    private var toast: Toast? = null

    private fun showToast(text: String?) {
        if (toast != null) {
            toast?.cancel()
        }
        toast = Toast.makeText(this, text, Toast.LENGTH_SHORT)
        toast?.show()
    }

    private val executor = Executors.newSingleThreadExecutor()

    private fun parsePhoto(data: Intent) {
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, data.data)
            //异步解析
            asyncThread {
                val result = CodeUtils.parseCode(bitmap)
                runOnUiThread {
                    LogUtils.d("result:$result")
                    showToast(result)
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    private fun asyncThread(runnable: Runnable) {
        executor.execute(runnable)
    }

    //fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>?, grantResults: IntArray?) {
    //    super.onRequestPermissionsResult(requestCode, permissions!!, grantResults!!)
    //    if (requestCode == REQUEST_CODE_READ_EXTERNAL_STORAGE && PermissionUtils.requestPermissionsResult(
    //            READ_EXTERNAL_STORAGE,
    //            permissions,
    //            grantResults)) {
    //        startPickPhoto()
    //    }
    //}

    /**
     * 开始选择图片
     */
    private fun startPickPhoto() {
        val pickIntent = Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(pickIntent, REQUEST_CODE_PHOTO)
    }


    /**
     * 扫码
     *
     * @param cls
     */
    private fun startScan(cls: Class<*>) {
        val intent = Intent(this, cls)
        startActivityForResult(intent, REQUEST_CODE_SCAN)
    }

    /**
     * 生成二维码/条形码
     *
     * @param isQRCode
     */
    private fun startGenerateCodeActivity(isQRCode: Boolean, title: String) {
        val intent = Intent(this, CodeActivity::class.java)
        intent.putExtra(KEY_IS_QR_CODE, isQRCode)
        intent.putExtra(KEY_TITLE, title)
        startActivity(intent)
    }

    /**
     * 点击选择图片识别 - 进行动态权限校验
     */
    private fun pickPhotoClicked() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                startPickPhoto()
            }
        } else {
            if (PermissionUtils.checkPermission(this, READ_EXTERNAL_STORAGE)) {
                startPickPhoto()
            } else {
                PermissionUtils.requestPermission(this, READ_EXTERNAL_STORAGE, REQUEST_CODE_READ_EXTERNAL_STORAGE)
            }
        }
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.btnMultiFormat -> startScan(MultiFormatScanActivity::class.java)
            R.id.btnQRCode -> startScan(QRCodeScanActivity::class.java)
            R.id.btnFullQRCode -> startScan(FullScreenQRCodeScanActivity::class.java)
            R.id.btnPickPhoto -> pickPhotoClicked()
            R.id.btnGenerateQrCode -> startGenerateCodeActivity(true, (v as Button).text.toString())
            R.id.btnGenerateBarcode -> startGenerateCodeActivity(false, (v as Button).text.toString())
        }
    }

    companion object{
        const val KEY_TITLE = "KEY_TITLE"
        const val KEY_IS_QR_CODE = "KEY_IS_QR_CODE"
    }
}

/**
 * 获取所有文件权限
 * 1.manifest中声明权限(targetVersion大于等于30时)：<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
 * 2.动态获取权限，获取之后执行对应操作
 */
fun requestFilePermission(activity: AppCompatActivity, permissionResult: ((ActivityResult) -> Unit)? = null) {
    val startForResult = activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        permissionResult?.invoke(result)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        if (!Environment.isExternalStorageManager()) {
            startForResult.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
        }
    } else {
        startForResult.launch(Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS))
    }
}